/* 
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.samples.app;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;

import com.google.android.samples.R;

import java.util.Map;

/**
 * This is an example of implementing an application service that runs locally
 * in the same process as the application.  The {@link ServiceStartArgumentsController}
 * class shows how to interact with the service. 
 *
 * <p>Notice the use of the {@link NotificationManager} when interesting things
 * happen in the service.  This is generally how background services should
 * interact with the user, rather than doing something more disruptive such as
 * calling startActivity().
 */
public class ServiceStartArguments extends Service implements Runnable
{
    @Override
    protected void onCreate()
    {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        // This is who should be launched if the user selects our persistent
        // notification.
        mInvokeIntent = new Intent(this, ServiceStartArgumentsController.class);

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.
        Thread thr = new Thread(null, this, "ServiceStartArguments");
        thr.start();
    }

    @Override
    protected void onStart(int startId, Bundle arguments)
    {
        System.out.println("Starting #" + startId + ": " + arguments);
        while (mServiceHandler == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }

        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = arguments;
        mServiceHandler.sendMessage(msg);
        Log.i("ServiceStartArguments", "Sending: " + msg);
    }

    @Override
    protected void onDestroy()
    {
        while (mServiceLooper == null) {
            synchronized (this) {
                try {
                    wait(100);
                } catch (InterruptedException e) {
                }
            }
        }
        mServiceLooper.quit();

        // Cancel the persistent notification.
        mNM.cancel(R.string.service_arguments_started);

        // Tell the user we stopped.
        mNM.notifyWithText(R.string.service_arguments_stopped,
                   getText(R.string.service_arguments_stopped),
                   NotificationManager.LENGTH_SHORT,
                   null);
    }

    public void run()
    {
        Looper.prepare();

        mServiceLooper = Looper.myLooper();
        mServiceHandler = new ServiceHandler();

        Looper.loop();
    }

    @Override
    public IBinder getBinder()
    {
        return null;
    }

    private final class ServiceHandler extends Handler
    {
        @Override
        public void handleMessage(Message msg)
        {
            Bundle arguments = (Bundle)msg.obj;
            String txt = getResources()
                    .getString(R.string.service_arguments_started);
            txt = txt + arguments.getString("name");

            Log.i("ServiceStartArguments", "Message: " + msg + ", " + txt);

            // Display a notification about us starting.  We use both a transient
            // notification and a persistent notification in the status bar.
            mNM.notifyWithText(R.string.service_arguments_started,
                       txt,
                       NotificationManager.LENGTH_SHORT,
                       new Notification(
                           R.drawable.stat_sample,
                           getText(R.string.service_start_arguments_label),
                           mInvokeIntent,
                           null,
                           null));

            // Normally we would do some work here...  for our sample, we will
            // just sleep for 10 seconds.
            long endTime = System.currentTimeMillis() + 5*1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }

            Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
            stopSelf(msg.arg1);
        }

    };

    private NotificationManager mNM;
    private Intent mInvokeIntent;
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
}

